package com.youxin.chat.gateway.filter;

import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson.JSONObject;
import com.youxin.auth.client.properties.AuthClientProperties;
import com.youxin.auth.client.utils.JwtTokenClientUtils;
import com.youxin.auth.utils.JwtUserInfo;
import com.youxin.base.BaseResultCode;
import com.youxin.base.TResult;
import com.youxin.chat.gateway.config.YouxinAuthProperties;
import com.youxin.chat.user.client.UserClient;
import com.youxin.chat.user.dto.UserInfoDto;
import com.youxin.common.adapter.IgnoreTokenConfig;
import com.youxin.context.BaseContextConstants;
import com.youxin.exception.BizException;
import com.youxin.exception.SystemException;
import com.youxin.utils.StrHelper;
import com.youxin.utils.StrPool;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 过滤器
 *
 * @author zuihou
 * @date 2019/07/31
 */
@Component
//@Order(0)
public class AccessFilter implements GlobalFilter {

    private static final Logger log = LoggerFactory.getLogger(AccessFilter.class);


    @Value("${spring.profiles.active:dev}")
    protected String profiles;
    @Autowired
    private AuthClientProperties authClientProperties;
    @Autowired
    private JwtTokenClientUtils jwtTokenClientUtils;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Reference(retries = 1,timeout = 10000)
    private UserClient userClient;

    @Resource
    private YouxinAuthProperties youxinAuthProperties;

    protected boolean isDev() {
        return !StrPool.PROD.equalsIgnoreCase(profiles);
    }

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    /**
     * 忽略应用级token
     *
     * @return
     */
    protected boolean isIgnoreToken(String uri) {
        List<String> list = youxinAuthProperties.getIgnoreUrls();
        if (list.isEmpty()) {
            return false;
        }
        return list.stream().anyMatch((url) ->
                uri.startsWith(url) || ANT_PATH_MATCHER.match(url, uri)
        );
    }

    protected String getTokenFromRequest(String headerName, ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String token = StrUtil.EMPTY;
        if (headers == null || headers.isEmpty()) {
            return token;
        }

        List<String> headerList = headers.get(headerName);
        if (headerList == null || headerList.isEmpty()) {
            return token;
        }
        token = headerList.get(0);

        if (StringUtils.isNotBlank(token)) {
            return token;
        }
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        if (queryParams == null || queryParams.isEmpty()) {
            return token;
        }
        return queryParams.getFirst(headerName);
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 不进行拦截的地址
        if (isIgnoreToken(request.getPath().toString())) {
            log.debug("access filter not execute");

            return chain.filter(exchange);
        }

        //获取token， 解析，然后想信息放入 heade
        //1, 获取token

        String userToken = getTokenFromRequest(authClientProperties.getUser().getHeaderName(), request);

        //2, 解析token
        UserInfoDto userInfo = null;


        try {
            userInfo = userClient.getUserInfoByToken(userToken);
        } catch (SystemException e) {
            return errorResponse(response, e.getMessage(), e.getCode(), 200);
        } catch (Exception e) {
            log.error("验证token出错",e);
            return errorResponse(response, "验证token出错", BaseResultCode.RECORD_NOT_EXISTS, 200);
        }
        if (userInfo == null) {
            return errorResponse(response, "用户未登录，请重新登录", BaseResultCode.RECORD_NOT_EXISTS, 200);
        }
        if (userInfo.getUserStatus() != 0) {
            return errorResponse(response, "账号已被锁定,请联系管理员!", BaseResultCode.ACCOUNT_LOCK, 200);
        }
        ServerHttpRequest.Builder mutate = request.mutate();


        addHeader(mutate, BaseContextConstants.JWT_KEY_USER_NO, userInfo.getUserNo());
        addHeader(mutate, BaseContextConstants.JWT_KEY_ACCOUNT, userInfo.getUserName());
        addHeader(mutate, BaseContextConstants.JWT_KEY_NAME, userInfo.getNickName());

        ServerHttpRequest build = mutate.build();
        return chain.filter(exchange.mutate().request(build).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (org.springframework.util.StringUtils.isEmpty(value)) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = StrHelper.encode(valueStr);
        mutate.header(name, valueEncode);
    }

    protected Mono<Void> errorResponse(ServerHttpResponse response, String errMsg, String errCode, int httpStatusCode) {
        TResult tokenError = TResult.build(errCode, errMsg);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSONObject.toJSONString(tokenError).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

}
